package com.file.parser;

import com.file.bo.ResponseData;
import com.file.bo.mail.BOSC;
import com.file.bo.mail.BOSCTran;
import com.file.constant.ErrorCode;
import com.file.parser.traprange.PDFTableExtractor;
import com.file.util.JsonUtils;
import com.google.common.base.Splitter;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

@Slf4j
public class BOSCPdfParser extends BasePdfParser {

    public ResponseData<String> parseBOSCPdfToJson(String daId, String filePath) {
        log.info("parseBOSCPdfToJson started, daId:{}", daId);
        String json = null;

        try {
            BOSC bosc = parseBOSCPdf(filePath);
            json = JsonUtils.convertObjectToJson(bosc);
        } catch (Exception e) {
            log.error("OnError|{}||{}|{}|{}|{}", ErrorCode.FILE_PARSE_EXCEPTION.getCode(), daId, "", "", "parseBOSCPdfToJson failed", e);
            return new ResponseData<String>(null, ErrorCode.FILE_PARSE_EXCEPTION.getCode(),
                    ErrorCode.FILE_PARSE_EXCEPTION.getMsg());
        }

        log.info("parseBOSCPdfToJson completed, daId:{}", daId);
        return new ResponseData<String>(json, ErrorCode.SUCCESS.getCode(), ErrorCode.SUCCESS.getMsg());
    }

    public BOSC parseBOSCPdf(String filePath) {
        String pdfHeaderText = parsePdfHeaderText(filePath);
//        System.out.println(pdfHeaderText);

        BOSC bosc = parseBOSCHeader(pdfHeaderText);
        List<BOSCTran> boscTrans = null;
        if (pdfHeaderText.contains("对方户名")) {
            boscTrans = parseBOSCTransWithCounterParty(filePath);
        } else {
            boscTrans = parseBOSCTransWithoutCounterParty(filePath);
        }
        bosc.setBoscTrans(boscTrans);
        return bosc;
    }

    public BOSC parseBOSCHeader(String pdfHeaderText) {
        BOSC bosc = new BOSC();
        bosc.setName(parsePdfHeaderField(pdfHeaderText, "姓名：|账号："));
        bosc.setAccountNo(parsePdfHeaderField(pdfHeaderText, "账号：|Name:"));
        bosc.setCurrency(parsePdfHeaderField(pdfHeaderText, "币种：|开户行："));
        bosc.setSubBranch(parsePdfHeaderField(pdfHeaderText, "开户行：|Currency:"));
        bosc.setQueryStartEndDate(parsePdfHeaderField(pdfHeaderText, "查询日期区间：|Query Start"));
        return bosc;
    }

    public List<BOSCTran> parseBOSCTransWithCounterParty(String filePath) {
        List<BOSCTran> boscTrans = new ArrayList<>();
        String transText = parseTransToText(filePath);
        List<List<String>> rowList = parseTransTextToTranFieldsList(transText);
        for (int i = 0; i < rowList.size(); i++) {
            List<String> cellList = rowList.get(i);
//            System.out.println(cellList);
            if (StringUtils.isNotBlank(cellList.get(0))) {
                BOSCTran boscTran = new BOSCTran();
                boscTran.setDate(cellList.get(0));
                boscTran.setSummary(cellList.get(1));
                boscTran.setCurrency(cellList.get(2));
                boscTran.setTransactionAmount(cellList.get(3));
                boscTran.setBalance(cellList.get(4));
                boscTran.setTransactionBranches(cellList.get(5));
                if (StringUtils.isBlank(cellList.get(6))) {
                    if (i > 0 && i < rowList.size() -1 && StringUtils.isBlank(rowList.get(i - 1).get(0)) && StringUtils.isBlank(rowList.get(i + 1).get(0)) && StringUtils.isNotBlank(rowList.get(i - 1).get(6)) && StringUtils.isNotBlank(rowList.get(i + 1).get(6))) {
                        boscTran.setCounterParty(rowList.get(i -1).get(6) + rowList.get(i + 1).get(6));
                    }
                } else {
                    boscTran.setCounterParty(cellList.get(6));
                }
                if (StringUtils.isBlank(cellList.get(7))) {
                    if (i > 0 && i < rowList.size() -1 && StringUtils.isBlank(rowList.get(i - 1).get(0)) && StringUtils.isBlank(rowList.get(i + 1).get(0)) && StringUtils.isNotBlank(rowList.get(i - 1).get(7)) && StringUtils.isNotBlank(rowList.get(i + 1).get(7))) {
                        boscTran.setTransactionChannel(rowList.get(i - 1).get(7) + rowList.get(i + 1).get(7));
                    }
                } else {
                    boscTran.setTransactionChannel(cellList.get(7));
                }
                boscTrans.add(boscTran);
            }
        }

        return boscTrans;
    }

    public List<BOSCTran> parseBOSCTransWithoutCounterParty(String filePath) {
        List<BOSCTran> boscTrans = new ArrayList<>();
        String transText = parseTransToText(filePath);
        List<List<String>> rowList = parseTransTextToTranFieldsList(transText);
        for (int i = 0; i < rowList.size(); i++) {
            List<String> cellList = rowList.get(i);
//            System.out.println(cellList);
            BOSCTran boscTran = new BOSCTran();
            boscTran.setDate(cellList.get(0));
            boscTran.setSummary(cellList.get(1));
            boscTran.setCurrency(cellList.get(2));
            boscTran.setTransactionAmount(cellList.get(3));
            boscTran.setBalance(cellList.get(4));
            boscTran.setTransactionBranches(cellList.get(5));
            boscTran.setTransactionChannel(cellList.get(6));
            boscTrans.add(boscTran);
        }

        return boscTrans;
    }

    public String parseTransToText(String filePath) {
        PDFTableExtractor extractor = (new PDFTableExtractor()).setSource(filePath);
        int pdfPageNumber = getPdfPageNumber(filePath);
        for (int i = 0; i < pdfPageNumber; i++) {
            int[] skipLines = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, -1, -2, -3, -4, -5, -6};
            extractor.exceptLine(i, skipLines);
        }
        return extractPdfToText(extractor);
    }

    public List<List<String>> parseTransTextToTranFieldsList(String transText) {
        // 这个List每个元素代表一条记录的文本字符串
        List<String> tranTextList = Splitter.on(System.getProperty("line.separator", "\n")).splitToList(transText);
        List<List<String>> tranFieldsList = new ArrayList<List<String>>();

        for (int i = 0; i < tranTextList.size() - 1; i++) {
            // 每一个wechatTranFieldList代表一条记录的所有字段，一个List一条记录
            List<String> wechatTranFields = Splitter.on(";").splitToList(tranTextList.get(i));
            Collections.addAll(tranFieldsList, wechatTranFields);
        }

        return tranFieldsList;
    }


    public static void main(String[] args) {
        BOSCPdfParser boscPdfParser = new BOSCPdfParser();
        ResponseData<String> responseData = boscPdfParser.parseBOSCPdfToJson("daid", "D:\\data\\file\\beehive-bosc\\上海银行-无交易对手信息.pdf");
        System.out.println(responseData.getData());

    }

}
